﻿using JWT9Demo.Entites;
using JWT9Demo.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;

namespace JWT9Demo.Controllers
{
   
    [Route("api/[controller]")]
    [ApiController]
    public class AuthController (IConfiguration configuration): ControllerBase
    {

        public static User user = new();
        [HttpPost("register")]
        public ActionResult<User> Register(UserDto request)
        {
            var hashedPassword = new PasswordHasher<User>().HashPassword(user, request.Password);
            user.Id = request.Id;
           user.UserName = request.UserName;
            user.PasswordHash = hashedPassword;
            user.Role = request.Role;

            return Ok(user);
        }

        [HttpPost("login")]
        public ActionResult<string> Login (UserDto request)
        {
            if (user.UserName!=request.UserName)
            {
                return BadRequest("没有找到用户");
            }
            if (new PasswordHasher<User>().VerifyHashedPassword(user,user.PasswordHash,request.Password)
                == PasswordVerificationResult.Failed)
            {
                return BadRequest("密码错误");
            }

            string token = CreateToken(user);
            return Ok(token);
        }

        [Authorize]
        [HttpGet]
        public IActionResult Authenticated()
        {
            return Ok("仅仅认证过用户登录");
        }

        [Authorize(Roles ="Admin,User")]
        [HttpGet("adminanduseronly")]
        public IActionResult Admin()
        {
            return Ok("Admin和User可以登录");
        }

        private string GenerateRefreshToken()
        {
            var randomNumber = new byte[32];
            using var rng = RandomNumberGenerator.Create();
            rng.GetBytes(randomNumber);
            return Convert.ToBase64String(randomNumber);
        }

        private async Task<string> GenerateAndSaveRenfreshToken()
        {
            var refreshToken = GenerateRefreshToken();
            user.RefreshToken = refreshToken;
            //await _context.SaveChangesAsync();
            return refreshToken;
        }

        private string CreateToken (User user)
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name,user.UserName),//在这里添加
                new Claim(ClaimTypes.NameIdentifier,user.Id.ToString()),//在这里添加
                new Claim(ClaimTypes.Role,user.Role)
            };
            var key = new SymmetricSecurityKey(
                Encoding.UTF8.GetBytes(configuration.GetValue<string>("AppSettings:Token")!));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha512);

            var tokenDescriptor = new JwtSecurityToken(
                issuer:configuration.GetValue<string>("AppSettings:Issuer"),
                audience: configuration.GetValue<string>("AppSettings:Audience"),
                claims: claims,
                expires: DateTime.UtcNow.AddDays(1),
                signingCredentials: creds
            );
           
            return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
        }
    }
}
